package com.meida.module.arc.provider.algorithm;

import com.meida.common.base.utils.FlymeUtils;
import com.meida.module.arc.client.entity.ArcCategory;
import com.meida.module.arc.provider.service.ArcCategoryService;
import com.meida.starter.shardingjdbc.base.MyStandardShardingAlgorithm;
import lombok.AllArgsConstructor;
import org.apache.shardingsphere.infra.executor.sql.log.SQLLogger;
import org.apache.shardingsphere.sharding.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.RangeShardingValue;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 自定义标准分片算法
 *
 * @author zyf
 */
@Component
@AllArgsConstructor
public class CustomModTableShardAlgorithm implements MyStandardShardingAlgorithm {

    private final ArcCategoryService categoryService;

    /**
     * 对应
     * @param collection
     * @param preciseShardingValue
     * @return
     */
    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<Long> preciseShardingValue) {
        //分片字段值对应categoryId
        Long value = preciseShardingValue.getValue();
        ArcCategory category = categoryService.getById(value);
        if (FlymeUtils.isNotEmpty(category)) {
            String tableName = category.getTableName();
            for (String name : collection) {
                if (name.endsWith(tableName)) {
                    return name;
                }
            }
        }
        throw new UnsupportedOperationException();
    }

    @Override
    public Collection<String> doSharding(Collection<String> collection, RangeShardingValue<Long> rangeShardingValue) {
        return collection;
    }
}